//
//  MyController.m
//  HarmonizePub
//
//  Created by rzhy on 2016/10/31.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "MyController.h"
#import "Config.h"
#import "User.h"
#import "InfoCenterController.h"
#import "ChoosePatientViewController.h"
#import "WebViewController.h"
#import "MyTableViewCell.h"
#import "MyHeadView.h"
#import "LoginController.h"
// 友盟
#import <UShareUI/UShareUI.h>

static NSString *CellIdentifier = @"Cell";

typedef NS_ENUM(NSUInteger, MyMenuItemType) {
    MyMenuItemTypeJump = 0,
    MyMenuItemTypeChoosePatient = 1,
    MyMenuItemTypeWebView = 2,
    MyMenuItemTypeShare = 3,
    MyMenuItemTypeVersionUpdate = 4
};

@interface MyController () <UITableViewDataSource, UITableViewDelegate, MyHeadViewDelegate>
{
    MyHeadView *_headView;
    NSArray *_dataArray;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation MyController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    UINib *nib = [UINib nibWithNibName:[MyTableViewCell registerName] bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
    [self dataArray];
}

- (void)dataArray {
    _dataArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"MyListData" ofType:@"plist"]];
//    BOOL isUpdateVersion = [UserDefaultsTool integerForKey:XHIsUpdateVersion];
//    if (isUpdateVersion) {
//        NSDictionary *dict = @{@"image" : @"Upload.png", @"title" : @"版本更新", @"jumpType" : @4, @"string" : @"VersionUpdate"};
//        NSMutableArray *arrayM = [_dataArray mutableCopy];
//        NSMutableArray *array = [arrayM[1] mutableCopy];
//        [array addObject:dict];
//        [arrayM setObject:array atIndexedSubscript:1];
//        _dataArray = [arrayM copy];
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:XHUserPath];
    _headView.user = user;
}

#pragma mark - headView
- (UIView *)createHeadView {
    if (_headView) return _headView;
    __weak typeof(self) weakSelf = self;
    _headView = [MyHeadView headViewWithTouchImageEventBlock:^{
        InfoCenterController *infoCenter = [[InfoCenterController alloc] init];
        [weakSelf.navigationController pushViewController:infoCenter animated:YES];
    }];
    _headView.delegate = self;
    return _headView;
}

- (void)headViewTouchLoginButtonEvent:(MyHeadView *)headView {
    LoginController *login = [[LoginController alloc] init];
    [self.currentViewController presentViewController:login animated:YES completion:nil];
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section)
        return [_dataArray[section - 1] count];
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section) return [MyTableViewCell cellHeight];
    return [MyHeadView height];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 1) return 8.0;
    return 0.01f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (indexPath.section == 0) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"HeadViewCell"];
        if (!cell)
            cell = (MyTableViewCell *)[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"HeadViewCell"];
        [cell addSubview:[self createHeadView]];
    } else {
        [cell cellShowDataWithDataDictionary:_dataArray[indexPath.section - 1][indexPath.row]];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dataDict = _dataArray[indexPath.section - 1][indexPath.row];
    MyMenuItemType type = [dataDict[@"jumpType"] integerValue];
    NSString *string = dataDict[@"string"];
    if (string.length) {
        switch (type) {
            case MyMenuItemTypeJump: {
                // 0: 正常跳转
                UIViewController *viewController = [[NSClassFromString(string) alloc] init];
                viewController.title = dataDict[@"title"];
                [self.navigationController pushViewController:viewController animated:YES];
                break;
            }
            case MyMenuItemTypeChoosePatient: {
                // 1: 选择就诊人
                [ChoosePatientViewController patientWithCurrentController:self nextController:string patientListType:XHPatientListTypeAll];
                break;
            }
            case MyMenuItemTypeWebView: {
                // 2: WebView
                WebViewController *web = [[WebViewController alloc] init];
                web.title = dataDict[@"title"];
                web.url = [URLTool webURLStringWithPathString:string token:[UserDefaultsTool stringForKey:XHToken]];
                [self.navigationController pushViewController:web animated:YES];
                break;
            }
            case MyMenuItemTypeShare: {
                // 3: 分享
                [self share];
                break;
            }
            case MyMenuItemTypeVersionUpdate: {
                // 4: 版本更新
                NSURL *url = [NSURL URLWithString:XHAppUrl];
                if ([[UIApplication sharedApplication] canOpenURL:url])
                    [[UIApplication sharedApplication] openURL:url];
                break;
            }
        }
    } else {
        [self setAlertViewWithMessage:XHAlertMsg];
    }
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.section;
}

#pragma mark - 分享
- (void)share {
    // 显示分享面板
    __weak typeof(self) weakSelf = self;
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        [weakSelf shareTextToPlatformType:platformType];
    }];
}

- (void)shareTextToPlatformType:(UMSocialPlatformType)platformType {
    // 创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    // 图片
    UIImage *image = [UIImage imageNamed:@"icon.png"];
    // web
    UMShareWebpageObject *web = [UMShareWebpageObject shareObjectWithTitle:@"新泰市第三人民医院" descr:@"下载新泰市第三人民医院App。" thumImage:image];
    web.webpageUrl = @"https://itunes.apple.com/cn/app/%E8%BF%9E%E6%B1%9F%E5%8E%BF%E5%8C%BB%E9%99%A2/id1321318471?mt=8";
    messageObject.shareObject = web;
    
    // 调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            XHLog(@"************ Share fail with error %@ *********", error.localizedDescription);
        }
    }];
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

@end
